package com.demo.pattern.proxy.dynamicProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

import java.lang.reflect.Proxy;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2022-05-26 22:53
 * @Description: ProxyFactory$
 */
public class ProxyFactory {

	private ProxyFactory(){};

	private static final ProxyFactory instance = new ProxyFactory();

	public static ProxyFactory getInstance() {
		return instance;
	}

	public Object getJdkProxy(Object obj){
        //动态的获取代理对象，没有代理类
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
				obj.getClass().getInterfaces(),
				(proxy, method, args1) -> {
					Object result = null;
					//增强逻辑
					System.out.println("中介(代理)收取服务费3000元");
					//调用原有逻辑
					result = method.invoke(obj, args1);
					System.out.println("客户信息买了3元");
					return result;
				});
	}

	/**
	 *
	 * @param obj 委托对象
	 * @return 代理对象
	 */
	public Object getCglibProxy(Object obj){
		return Enhancer.create(obj.getClass(),
				(MethodInterceptor) (obj1, method, objects, methodProxy) -> {
					//obj:代理对象的引用，method:动态执行到的方法，objects:参数，methodProxy:对当前执行到的方法的一个封装
					Object result = null;
					//增强逻辑
					System.out.println("中介(代理)收取服务费3000元");
					//调用原有逻辑
					result = method.invoke(obj, objects);
					System.out.println("客户信息买了3元");
					return result;
				});
	}
}
